package com.joinlabs.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.joinlabs.entity.MessageBean;

@Component
@ServerEndpoint(value="/websocket/{userId}")
public class DialogServer {
	private Logger logger = LoggerFactory.getLogger(DialogServer.class);
	
	private static String userId;
	//用来记录sessionId和该session进行绑定
	private static Map<String,Session> map = new HashMap<String, Session>();
	//用来存放每个客户端对应的DialogServer对象。
  //  private static CopyOnWriteArraySet<DialogServer> webSocketSet = new CopyOnWriteArraySet<DialogServer>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
	private Session session;
	
	public Session getSession() {
		return session;
	}
	
	//连接时执行
    @OnOpen
    public void onOpen(@PathParam("userId") String userId,Session session) throws IOException{
        
    	
    	//1)把当前请求连接的userid作为键，当前创建的 DialogServer对象(初始化session对象)作为 值，存到map中
    	
    	
    	
    	System.out.println(this);
    	
    	this.userId = userId;
        this.session = session;
        //把会话和会话id封装到map集合中
        map.put(userId, session);
        System.out.println(userId);
        //加到set中
       // webSocketSet.add(this);
        //System.out.println("有新连接加入:"+userId+",当前在线人数为" + webSocketSet.size());
        //this.session.getAsyncRemote().sendText("恭喜"+userId+"成功连接上WebSocket(其频道号："+session.getId()+")-->当前在线人数为："+webSocketSet.size());
     
    }
    
    //关闭时执行
    @OnClose
    public void onClose(){
        logger.debug("连接：{} 关闭",this.userId);
    }
    
    //收到消息时执行
    @OnMessage
    public void onMessage(String message, Session session,@PathParam("userId") String userId) throws IOException {
    	
    	
    	
    	//从客户端传过来的数据是json数据，所以这里使用jackson进行转换为SocketMsg对象
    	ObjectMapper objectMapper = new ObjectMapper();
        MessageBean socketMsg;
    	//要在客户端封装msgBean对象
        socketMsg = objectMapper.readValue(message, MessageBean.class);
        
        //找到 接受者的用户id,去map中查询。
        //查得到  ，找出对应session对象 ,发送消息
        
        System.out.println(socketMsg);
        //logger.debug("收到用户{}的消息{}",this.userId,message);
        //session.getBasicRemote().sendText("收到 "+this.userId+" 的消息 "); //回复用户
        //单聊.需要找到发送者和接受者.
        
        //socketMsg.setFromUser(session.getId());//发送者.
        Session fromSession = map.get(socketMsg.getFromUser());
        Session toSession = map.get(socketMsg.getToUser());
        //发送给接受者.
        if(toSession != null){
            //发送给发送者.
            fromSession.getAsyncRemote().sendText(socketMsg.getMsg());
            //toSession.getAsyncRemote().sendText(userId+"："+socketMsg.getMsg());
        }else{
            //发送给发送者.
            fromSession.getAsyncRemote().sendText("系统消息：对方不在线或者您输入的频道号不对");
        }
    }
    
    //连接错误时执行
    @OnError
    public void onError(Session session, Throwable error){
        logger.debug("用户id为：{}的连接发送错误",this.userId);
        error.printStackTrace();
    }
}
